﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace FormView.UI
{
	public class FormResult
	{
		public object Result { get; }

		public FormResult(object result)
		{
			Result = result;
		}

		public int CastToInt()
		{
			AssertResultNotNull();
			if (Result.GetType() == typeof(int))
			{
				return (int) Result;
			}

			return (int) Convert.ChangeType(Result, typeof(int));
		}

		public long CastToLong()
		{
			AssertResultNotNull();
			if (Result.GetType() == typeof(long))
			{
				return (long)Result;
			}

			return (long)Convert.ChangeType(Result, typeof(long));
		}

		public bool CastToBool()
		{
			AssertResultNotNull();
			if (Result.GetType() == typeof(bool))
			{
				return (bool)Result;
			}

			return (bool)Convert.ChangeType(Result, typeof(bool));
		}

		public double CastToDouble()
		{
			AssertResultNotNull();
			if (Result.GetType() == typeof(double))
			{
				return (double)Result;
			}

			return (double)Convert.ChangeType(Result, typeof(double));
		}

		public string CastToString()
		{
			AssertResultNotNull();
			return Result.ToString();
		}

		public List<FormResult> CastToList()
		{
			AssertResultNotNull();
			if (Result is IEnumerable res)
			{
				LinkedList<FormResult> formResults = new LinkedList<FormResult>();
				IEnumerator enumerator = res.GetEnumerator();
				while (enumerator.MoveNext())
				{
					formResults.AddLast(new FormResult(enumerator.Current));
				}

				return formResults.ToList();
			}

			throw new TypeAccessException($"FormResult:{Result.GetType()}，不是一个可迭代类型");
		}

		public FormResult[] CastToArray()
		{
			AssertResultNotNull();
			return CastToList().ToArray();
		}

		public bool IsSuccess() => Result != null;

		private void AssertResultNotNull()
		{
			if (Result == null)
			{
				throw new ArgumentException("当前结果为NULL");
			}
		}
	}
}
